package com.train.api;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;

import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

public class TicketLeft {
	private static CookieStore cookieStore = new BasicCookieStore();
	private static HttpContext localContext = new BasicHttpContext();
	private static String mainURL = "http://dynamic.12306.cn/otsquery/query/queryRemanentTicketAction.do";
	
	public static int RESPONSE_NO_RESPONSE       = 0;
	public static int RESPONSE_OK                = 2;

	public static JSONArray result = null;
	
	public static boolean init(){
		boolean result = false;
		try{
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("method", "init"));
			byte[] resp = Util.Get(mainURL, params, localContext, cookieStore);
			if (resp != null){
				result = true;
			}
		}catch(Exception e){
			result = false;
		}
		return result;
	}
	
	public static String getLeft(String startStation,
			              String arriveStation,
			              int year,
			              int month,
			              int day){
		String result = null;
		try{
			String sYear = Integer.toString(year);
			String sMonth = month >= 10 ? Integer.toString(month) : "0" + Integer.toString(month);
			String sDay = day >= 10 ? Integer.toString(day) : "0" + Integer.toString(day);
			String date = String.format("%s-%s-%s", sYear, sMonth, sDay);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("method", "queryLeftTicket"));
			params.add(new BasicNameValuePair("orderRequest.train_date", date));
			params.add(new BasicNameValuePair("orderRequest.from_station_telecode", TeleCode.GetTeleCode(startStation)));
			params.add(new BasicNameValuePair("orderRequest.to_station_telecode", TeleCode.GetTeleCode(arriveStation)));
			params.add(new BasicNameValuePair("orderRequest.train_no", ""));
			params.add(new BasicNameValuePair("trainPassType", "QB"));
			params.add(new BasicNameValuePair("trainClass", "QB%23D%23Z%23T%23K%23QT%23"));
			params.add(new BasicNameValuePair("includeStudent", "00"));
			params.add(new BasicNameValuePair("seatTypeAndNum", ""));
			params.add(new BasicNameValuePair("orderRequest.start_time_str", "00%3A00--24%3A00"));
			byte[] resp = Util.Get(mainURL, params, localContext, cookieStore);
			result = new String(resp);
		}catch(Exception e){
			result = null;
		}
		return result;
	}
}
